const { spawn } = require('child_process');
const path = require('node:path')
const axios = require("axios")
const fs = require("fs")
const CONSTANTS = require("./constant")

class download{
  constructor(downloadUrl){
    // Aria2 可执行文件路径
    this.ARIA = path.join(__dirname, 'aria2c.exe');
    this.downloadUrl = downloadUrl || 'https://udomain.dl.sourceforge.net/project/openmediavault/6.5.0/openmediavault_6.5.0-amd64.iso';
    this.aria2Gid = null;
    this.aria2Process = null;
    this.accumulatedData  = "";
  }

  config(){
    const conf = path.join(__dirname, 'aria2.conf')
    const configInit = `--conf-path=${conf}`;
    return [configInit, this.downloadUrl]
  }

  async start(){
    this.aria2Process = await spawn(this.ARIA, this.config());
    this.listenInfo()
  }

  parseAria2Gid(output) {
    // 你可能需要编写一个函数来解析 Aria2 输出，以提取 GID（任务标识符）
    // 示例：假设 Aria2 输出中包含类似 "GID: xxx" 的行
    const match = output.match(/\[#[0-9a-f]+\s+(\d+)MiB/);
    return match ? match[1] : null;
  }
  listenInfo(){
    // 处理 Aria2 进程的输出
    this.aria2Process.stdout.on('data', (data) => {
      this.accumulatedData += data.toString();
       // 根据实际输出格式，判断是否包含有关下载进度的信息
      if (this.accumulatedData.includes('Downloading') && this.accumulatedData.includes('ETA')) {
        console.log(`Aria2--->res: ${this.accumulatedData}`);
        this.aria2Gid = this.parseAria2Gid(this.accumulatedData);
        this.accumulatedData = '';  // 重置累积的数据
      }
    });

    // 处理 Aria2 进程的错误
    this.aria2Process.stderr.on('data', (data) => {
      console.error(`Aria2 stderr: ${data}`);
    });

     // 处理 Aria2 进程关闭事件
    this.aria2Process.on('close', (code) => {
      console.log(`Aria2 process exited with code ${code}`);
    });
  }

    // 发送 Aria2 RPC 请求
    async sendAria2Rpc (method, gid) {
      try {
        const requestData = {
          jsonrpc: '2.0',
          id: '1',
          method: `aria2.${method}`,
          params: [`token:${CONSTANTS.aria2RpcToken}`, gid],
        };
        console.log('请求的数据:', requestData); // 添加这行输出
        const response = await axios.post(
            CONSTANTS.aria2RpcUrl, 
            requestData,
            {
              headers: {
                'Content-Type': 'application/json',
              },
            }
        );
  
        console.log(`Aria2 RPC response:`, response.data);
      } catch (error) {
        console.error('Error sending Aria2 RPC request:', error.message);
      }
    }
  
    // 暂停下载
    pauseDownload() {
      console.log('GID是否存在:', this.aria2Gid); // 添加这行输出
      this.sendAria2Rpc('pause', this.aria2Gid);
    }

      // 继续下载
  resumeDownload() {
    this.sendAria2Rpc('unpause', this.aria2Gid);
  }

}



module.exports = {
  download
}